package com.efounder.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.addressselector.BottomDialog;
import com.efounder.addressselector.OnAddressSelectedListener;
import com.efounder.addressselector.model.City;
import com.efounder.addressselector.model.County;
import com.efounder.addressselector.model.Province;
import com.efounder.addressselector.model.Street;
import com.efounder.bean.Address;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.AbStrUtil;
import com.efounder.util.DialogUtil;
import com.efounder.util.LoadingDataUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.MallRequestUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import static com.efounder.utils.MallRequestUtil.ADDRESS_UPDATE_URL;

/**
 * Created by will on 18-3-15.
 * @author will
 */

public class MallEditAddressNewActivity extends BaseActivity{

    private String TAG = this.getClass().getSimpleName();

    private int position;
    private List<Address> addresses;
    private SwitchCompat defaultAddressCheck;
    private EditText etDistrict, etPhone, etName, etSpecific;

    /**
     * 删除地址按钮
     */
    private TextView tvDeleteAddress;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mall_layout_add_address_new);
        Bundle bundle = getIntent().getExtras();
        addresses = (List<Address>)bundle.get("address");
        position = bundle.getInt("position");
        initView();
    }

    public void initView() {
        tvDeleteAddress = (TextView) findViewById(R.id.tv_delete_address);
        tvDeleteAddress.setVisibility(View.VISIBLE);
        tvDeleteAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.showDialogWithCancle(MallEditAddressNewActivity.this, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteAddress(position);
                    }
                },getString(R.string.common_text_hint),getString(R.string.mail_address_delete)
                        ,getString(R.string.common_text_confirm),getString(R.string.common_text_cancel));

            }
        });
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.mail_edit_address);
        TextView tvSaveBtn = (TextView) findViewById(R.id.tv_save);
        tvSaveBtn.setVisibility(View.VISIBLE);
        tvSaveBtn.setText(R.string.common_text_save);
        tvSaveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap<String, String> map = new HashMap<>();
                if (!etPhone.getText().toString().equals("")) {
                    if (!AbStrUtil.isMobileNo(etPhone.getText().toString())){
                        ToastUtil.showToast(MallEditAddressNewActivity.this, R.string.mail_enter_correct_phone_number);
                        return;
                    }else{
                        addresses.get(position).setPhone(etPhone.getText().toString());
                        map.put("phone", etPhone.getText().toString());
                    }
                }else {
                    ToastUtil.showToast(MallEditAddressNewActivity.this, R.string.mail_enter_complete_info);
                    return;
                }
                if (!etName.getText().toString().equals("")){
                    addresses.get(position).setUserName(etName.getText().toString());
                    map.put("userName", etName.getText().toString());
                }else {
                    ToastUtil.showToast(MallEditAddressNewActivity.this, R.string.mail_enter_complete_info);
                    return;
                }
                if(!etSpecific.getText().toString().equals("")){
                    addresses.get(position).setAddress(etSpecific.getText().toString());
                    map.put("address", etSpecific.getText().toString());
                }else {
                    ToastUtil.showToast(MallEditAddressNewActivity.this, R.string.mail_enter_complete_info);
                    return;
                }
                if (!etDistrict.getText().toString().equals("")) {
                    addresses.get(position).setArea(etDistrict.getText().toString());
                    map.put("area", etDistrict.getText().toString());
                }else {
                    ToastUtil.showToast(MallEditAddressNewActivity.this, R.string.mail_enter_complete_info);
                    return;
                }
                addresses.get(position).setIsSelected(defaultAddressCheck.isChecked() ? "1" : "0");
                map.put("addressId", addresses.get(position).getAddressId());
                map.put("userId", EnvironmentVariable.getUserName());
                map.put("isSelected", defaultAddressCheck.isChecked() ? "1" : "0");

                MallRequestUtil.getRequest(TAG, ADDRESS_UPDATE_URL, map, new MallRequestUtil.MallRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        Log.e("MallCart", response);
                        String addressId = addresses.get(position).getAddressId();
                        Intent intent = new Intent();
                        intent.putExtra("addressId", addressId);
                        setResult(RESULT_OK, intent);
                        finish();
                        finish();
                    }

                    @Override
                    public void onFail(String error) {

                    }
                });
            }
        });
        etName = (EditText) findViewById(R.id.et_address_name);
        etPhone = (EditText) findViewById(R.id.et_address_phone);
        etDistrict = (EditText) findViewById(R.id.et_address_district);
        etSpecific = (EditText) findViewById(R.id.et_address_specific);
        String userName = addresses.get(position).getUserName();
        String phone = addresses.get(position).getPhone();
        String area = addresses.get(position).getArea();
        String address = addresses.get(position).getAddress();
        etName.setText(userName);
        etName.setSelection(userName.length());
        etPhone.setText(phone);
        etPhone.setSelection(phone.length());
        etDistrict.setText(area);
        etDistrict.setSelection(area.length());
        etSpecific.setText(address);
        etSpecific.setSelection(address.length());
//        TextView tvSave = (TextView) findViewById(R.id.tv_save_address);
        defaultAddressCheck = (SwitchCompat) findViewById(R.id.switch_default_address);
        boolean isDefault = "1".equals(addresses.get(position).getIsSelected());
        defaultAddressCheck.setChecked(isDefault);
        defaultAddressCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            }
        });

        etPhone.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO) {
                    etDistrict.performClick();
                }
                return true;
            }
        });
        etDistrict.setInputType(InputType.TYPE_NULL);
        etDistrict.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final BottomDialog dialog = new BottomDialog(MallEditAddressNewActivity.this);
                dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
                    @Override
                    public void onAddressSelected(Province province, City city, County county, Street street) {
                        etDistrict.setText(province.name + city.name + county.name);
                        etDistrict.onEditorAction(EditorInfo.IME_ACTION_NEXT);
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });
    }
//    @Override
//    public void finish() {
//        super.finish();
//        this.overridePendingTransition(R.anim.bottom_dialog_exit,0);
//    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }

    /**
     * 删除地址接口请求
     * @param position 删除地址的下标
     */
    private void deleteAddress(final int position){
        Address address = addresses.get(position);
        HashMap<String,String> map = new HashMap<>();
        map.put("addressId",address.getAddressId());
        map.put("userId", EnvironmentVariable.getUserName());
        LoadingDataUtil.show();
        MallRequestUtil.postRequest(TAG, MallRequestUtil.ADDRESS_DELETE_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtil.dismiss();
                try {
                    String result =  new JSONObject(response).optString("result");
                    if(result.equals(MallRequestUtil.SUCCESS)){
                        //删除成功，关闭页面
                        finish();

                    }else {
                        ToastUtil.showToast(MallEditAddressNewActivity.this,R.string.mall_delete_fail);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtil.showToast(MallEditAddressNewActivity.this,R.string.mall_delete_fail);
                }
            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(MallEditAddressNewActivity.this,R.string.mall_delete_fail);
                LoadingDataUtil.dismiss();
            }
        });
    }
}
